package cn.dome.mysql.datasource.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.dome.mysql.datasource.pay.Pay;
import cn.dome.mysql.datasource.PayRepository.PayRepository;
import cn.dome.mysql.datasource.UserRepository.UserRepository;
import cn.dome.mysql.datasource.user.User;
import lombok.extern.slf4j.Slf4j;

/**
 * @author jetlag
 * @description
 * @date 2019/6/10 18:05
 **/
@Slf4j
@RestController
public class Controller {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PayRepository payRepository;

    @RequestMapping(value = "user")
    public void user() {
        List<User> all = userRepository.findAll();
        System.out.println(all);
    }

    @RequestMapping(value = "pay")
    public void pay() {
        List<Pay> all = payRepository.findAll();
        System.out.println(all);
    }

    @RequestMapping("/singleFile")
    public void singleFileUpload(@RequestParam(name = "file") MultipartFile file) {
        if (file.isEmpty()) {
            log.error("请先选择上传的文件");
        }
        String fileFormat = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName = String.valueOf(System.currentTimeMillis()) + fileFormat;
        String fileDate =  new SimpleDateFormat("yyyyMMdd").format(new Date());
        String fileServer = "http://47.75.220.7/pack/temp/";
        String filePath = "/data/center/pack/temp/" + fileDate + "/" + newFileName;
        //String filePath = "E:\\data\\center\\pack\\temp" + fileDate + "\\" + newFileName;
        log.info("========== UploadController ========== singleFileUpload  start");
        String absolutePath = new File(filePath).getAbsolutePath();
        File dest = new File(absolutePath);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            boolean flag = dest.getParentFile().mkdirs();
            if (!flag) {
                log.error("上传文件失败，请稍后重试");
            }
        }
        try {
            file.transferTo(dest);
            log.info("========== UploadController ========== singleFileUpload successful! result is [{}]");
    } catch (IllegalStateException | IOException e) {
            log.info("========== UploadController ========== singleFileUpload failed , file name is [{}]", newFileName);
        }

    }
}
